<template>
  <div class="order-detail-container">
    <div class="page-header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="page-title">订单详情</span>
        </template>
      </el-page-header>
    </div>
    
    <div v-loading="loading" class="detail-content">
      <!-- 订单基本信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(orderInfo.status)">
              {{ getOrderStatusText(orderInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderInfo.createTime }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag type="info">{{ getPaymentMethodText(orderInfo.paymentMethod) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ orderInfo.payTime || '未支付' }}</el-descriptions-item>
          <el-descriptions-item label="订单来源">{{ orderInfo.source || '网站' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 用户信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>用户信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="用户ID">{{ orderInfo.userId }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ orderInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ orderInfo.email || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ orderInfo.registerTime }}</el-descriptions-item>
          <el-descriptions-item label="购买次数">{{ orderInfo.purchaseCount || 1 }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 收货信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>收货信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="收货人">{{ orderInfo.receiver }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderInfo.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">
            {{ orderInfo.receiverAddress }}
          </el-descriptions-item>
          <el-descriptions-item v-if="orderInfo.status !== 'pending_payment'" label="物流公司">
            {{ orderInfo.logisticsCompany || '未发货' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="orderInfo.status !== 'pending_payment'" label="物流单号">
            <template v-if="orderInfo.trackingNo">
              {{ orderInfo.trackingNo }}
              <el-button type="primary" link size="small" style="margin-left: 10px" @click="handleLogistics">查看物流</el-button>
            </template>
            <template v-else>未发货</template>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 订单商品 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>订单商品</span>
          </div>
        </template>
        <el-table :data="orderInfo.items" style="width: 100%">
          <el-table-column prop="id" label="商品ID" width="80" />
          <el-table-column label="商品图片" width="100">
            <template #default="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="specs" label="规格" width="140" />
          <el-table-column prop="price" label="单价" width="100" sortable>
            <template #default="scope">
              ¥{{ Number(scope.row.price).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="120" sortable>
            <template #default="scope">
              ¥{{ (Number(scope.row.price) * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 订单金额 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>订单金额</span>
          </div>
        </template>
        <div class="amount-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="商品总价">¥{{ Number(orderInfo.totalProductAmount).toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="运费">¥{{ Number(orderInfo.freight).toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="优惠金额">-¥{{ Number(orderInfo.discountAmount).toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="实付金额" class="highlight-row">
              <span class="highlight-text">¥{{ Number(orderInfo.totalAmount).toFixed(2) }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      
      <!-- 订单操作 -->
      <el-card class="detail-card" v-if="orderInfo.status !== 'completed' && orderInfo.status !== 'cancelled'">
        <template #header>
          <div class="card-header">
            <span>订单操作</span>
          </div>
        </template>
        <div class="action-buttons">
          <el-button
            v-if="orderInfo.status === 'pending_payment'"
            type="warning"
            @click="handleCancel"
          >
            取消订单
          </el-button>
          <el-button
            v-if="orderInfo.status === 'paid'"
            type="success"
            @click="handleShip"
          >
            发货
          </el-button>
          <el-button
            v-if="orderInfo.status === 'shipped'"
            type="primary"
            @click="handleComplete"
          >
            确认收货
          </el-button>
          <el-button
            v-if="['paid', 'pending_shipment', 'shipped'].includes(orderInfo.status)"
            type="danger"
            @click="handleRefund"
          >
            申请退款
          </el-button>
        </div>
      </el-card>
      
      <!-- 订单日志 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>订单日志</span>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in orderInfo.logs"
            :key="index"
            :timestamp="activity.time"
            :type="index === 0 ? 'primary' : ''"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>
    
    <!-- 物流信息对话框 -->
    <el-dialog v-model="logisticsVisible" title="物流信息" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="物流公司">{{ logistics.company }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ logistics.trackingNo }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ logistics.shipTime }}</el-descriptions-item>
      </el-descriptions>

      <el-timeline class="logistics-timeline">
        <el-timeline-item
          v-for="(item, index) in logistics.records"
          :key="index"
          :timestamp="item.time"
          :type="index === 0 ? 'primary' : ''"
        >
          {{ item.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
    
    <!-- 发货对话框 -->
    <el-dialog v-model="shipDialogVisible" title="发货" width="500px">
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="120px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰快递" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
            <el-option label="邮政EMS" value="EMS" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialogVisible" title="申请退款" width="500px">
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="120px"
      >
        <el-form-item label="退款金额" prop="amount">
          <el-input-number
            v-model="refundForm.amount"
            :min="0"
            :max="orderInfo.totalAmount"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-select v-model="refundForm.reason" placeholder="请选择退款原因" style="width: 100%">
            <el-option label="商品质量问题" value="quality_issue" />
            <el-option label="商品损坏" value="damaged" />
            <el-option label="商品与描述不符" value="not_as_described" />
            <el-option label="发货太慢" value="slow_shipping" />
            <el-option label="商品缺货" value="out_of_stock" />
            <el-option label="客户不想要了" value="customer_changed_mind" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="refundForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入退款备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefund" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const orderId = route.params.id

// 数据加载状态
const loading = ref(true)
const submitLoading = ref(false)

// 订单信息
const orderInfo = ref({
  id: 0,
  orderNo: '',
  userId: 0,
  username: '',
  phone: '',
  email: '',
  registerTime: '',
  purchaseCount: 0,
  status: '',
  paymentMethod: '',
  createTime: '',
  payTime: '',
  receiver: '',
  receiverPhone: '',
  receiverAddress: '',
  logisticsCompany: '',
  trackingNo: '',
  source: '',
  items: [],
  totalProductAmount: 0,
  freight: 0,
  discountAmount: 0,
  totalAmount: 0,
  logs: []
})

// 物流信息
const logisticsVisible = ref(false)
const logistics = ref({
  company: '',
  trackingNo: '',
  shipTime: '',
  records: []
})

// 发货对话框
const shipDialogVisible = ref(false)
const shipFormRef = ref(null)
const shipForm = reactive({
  company: '',
  trackingNo: ''
})

const shipRules = {
  company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
  trackingNo: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
}

// 退款对话框
const refundDialogVisible = ref(false)
const refundFormRef = ref(null)
const refundForm = reactive({
  amount: 0,
  reason: '',
  remark: ''
})

const refundRules = {
  amount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }],
  reason: [{ required: true, message: '请选择退款原因', trigger: 'change' }]
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 'pending_payment':
      return 'warning'
    case 'paid':
    case 'pending_shipment':
      return 'success'
    case 'shipped':
      return 'info'
    case 'completed':
      return 'success'
    case 'cancelled':
      return 'danger'
    case 'refunding':
      return 'warning'
    case 'refunded':
      return 'info'
    default:
      return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'pending_payment':
      return '待付款'
    case 'paid':
      return '已付款'
    case 'pending_shipment':
      return '待发货'
    case 'shipped':
      return '已发货'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    case 'refunding':
      return '退款中'
    case 'refunded':
      return '已退款'
    default:
      return '未知'
  }
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  switch (method) {
    case 'alipay':
      return '支付宝'
    case 'wechat':
      return '微信支付'
    case 'bank':
      return '银行卡'
    default:
      return '未知'
  }
}

// 返回上一页
const goBack = () => {
  router.push('/shop/orders')
}

// 获取订单详情
const fetchOrderDetail = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const { data } = await getOrderDetail(orderId)
    // orderInfo.value = data
    
    // 模拟数据
    setTimeout(() => {
      orderInfo.value = {
        id: Number(orderId),
        orderNo: `ORD${String(2023050000 + Number(orderId)).padStart(10, '0')}`,
        userId: 10086,
        username: 'user123',
        phone: '13800138000',
        email: 'user123@example.com',
        registerTime: '2022-01-15 10:30:00',
        purchaseCount: 5,
        status: 'shipped',
        paymentMethod: 'alipay',
        createTime: '2023-05-20 10:30:00',
        payTime: '2023-05-20 10:35:00',
        receiver: '张三',
        receiverPhone: '13900139000',
        receiverAddress: '北京市海淀区中关村南大街5号',
        logisticsCompany: '顺丰快递',
        trackingNo: 'SF1234567890',
        source: '网站',
        items: [
          {
            id: 101,
            name: '金银花',
            image: 'https://via.placeholder.com/200',
            specs: '250g/袋',
            price: 29.90,
            quantity: 2
          },
          {
            id: 102,
            name: '当归',
            image: 'https://via.placeholder.com/200',
            specs: '100g/袋',
            price: 35.50,
            quantity: 1
          },
          {
            id: 103,
            name: '黄芪',
            image: 'https://via.placeholder.com/200',
            specs: '150g/袋',
            price: 42.80,
            quantity: 3
          }
        ],
        totalProductAmount: 250.60,
        freight: 10.00,
        discountAmount: 20.00,
        totalAmount: 240.60,
        logs: [
          { time: '2023-05-21 09:30:00', content: '商家已发货 [操作人: admin]' },
          { time: '2023-05-20 11:00:00', content: '系统已通知商家发货 [系统]' },
          { time: '2023-05-20 10:35:00', content: '买家已付款 [支付宝]' },
          { time: '2023-05-20 10:30:00', content: '买家创建订单 [user123]' }
        ]
      }
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('获取订单详情失败', error)
    ElMessage.error('获取订单详情失败')
    loading.value = false
  }
}

// 查看物流
const handleLogistics = () => {
  // 实际应用中应该调用API获取物流信息
  // const { data } = await getLogisticsInfo(orderInfo.value.id)
  // logistics.value = data
  
  // 模拟数据
  logistics.value = {
    company: orderInfo.value.logisticsCompany,
    trackingNo: orderInfo.value.trackingNo,
    shipTime: '2023-05-21 09:30:00',
    records: [
      { time: '2023-05-23 14:30:00', content: '已签收，签收人：本人' },
      { time: '2023-05-23 11:20:00', content: '快件已到达[北京市海淀区西二旗站]，快递员正在派送' },
      { time: '2023-05-22 18:30:00', content: '快件已到达[北京转运中心]' },
      { time: '2023-05-22 09:15:00', content: '快件已从[上海市浦东新区]发出' },
      { time: '2023-05-21 20:30:00', content: '快件已到达[上海转运中心]' },
      { time: '2023-05-21 09:30:00', content: '商家已发货' }
    ]
  }
  
  logisticsVisible.value = true
}

// 发货
const handleShip = () => {
  shipForm.company = ''
  shipForm.trackingNo = ''
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = () => {
  shipFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      // 实际应用中应该调用API
      // await updateOrderStatus(orderInfo.value.id, {
      //   status: 'shipped',
      //   logisticsCompany: shipForm.company,
      //   trackingNo: shipForm.trackingNo
      // })
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '发货成功'
      })
      
      // 关闭对话框并刷新数据
      shipDialogVisible.value = false
      fetchOrderDetail()
    } catch (error) {
      console.error('发货失败', error)
      ElMessage({
        type: 'error',
        message: '发货失败'
      })
    } finally {
      submitLoading.value = false
    }
  })
}

// 取消订单
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await updateOrderStatus(orderInfo.value.id, { status: 'cancelled' })
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '订单取消成功'
      })
      
      // 刷新数据
      fetchOrderDetail()
    } catch (error) {
      console.error('订单取消失败', error)
      ElMessage({
        type: 'error',
        message: '订单取消失败'
      })
    }
  }).catch(() => {})
}

// 确认收货
const handleComplete = () => {
  ElMessageBox.confirm('确定要确认收货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await updateOrderStatus(orderInfo.value.id, { status: 'completed' })
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '确认收货成功'
      })
      
      // 刷新数据
      fetchOrderDetail()
    } catch (error) {
      console.error('确认收货失败', error)
      ElMessage({
        type: 'error',
        message: '确认收货失败'
      })
    }
  }).catch(() => {})
}

// 申请退款
const handleRefund = () => {
  refundForm.amount = orderInfo.value.totalAmount
  refundForm.reason = ''
  refundForm.remark = ''
  refundDialogVisible.value = true
}

// 确认退款
const confirmRefund = () => {
  refundFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      // 实际应用中应该调用API
      // await applyRefund(orderInfo.value.id, refundForm)
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '退款申请已提交'
      })
      
      // 关闭对话框并刷新数据
      refundDialogVisible.value = false
      fetchOrderDetail()
    } catch (error) {
      console.error('申请退款失败', error)
      ElMessage({
        type: 'error',
        message: '申请退款失败'
      })
    } finally {
      submitLoading.value = false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail-container {
  .page-header {
    margin-bottom: 20px;
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .page-title {
      font-size: 18px;
      font-weight: bold;
    }
  }
  
  .detail-content {
    .detail-card {
      margin-bottom: 20px;
      
      .card-header {
        font-weight: bold;
      }
      
      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .amount-info {
    width: 400px;
    margin-left: auto;
    
    .highlight-row {
      :deep(.el-descriptions-item__label) {
        background-color: #f0f9eb;
        font-weight: bold;
      }
      
      .highlight-text {
        color: #f56c6c;
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
  
  .logistics-timeline {
    margin-top: 15px;
    padding: 10px;
  }
}
</style> 